﻿
namespace SistemaLogistica.Windows.Forms.Almacen.Operaciones
{
    using System;
    using System.Drawing;
    using System.Windows.Forms;
    using EDOSwit.Controls.DataGridView;
    using EDOSwit.Controls.Helpers;
    using EDOSwit.Controls.Types;
    using EDOSwit.Controls.UserControls;
    using SistemaLogistica.Business.Entities;
    using SistemaLogistica.Business.Entities.Types;
    using SistemaLogistica.Business.Logic;
    using SistemaLogistica.Windows.Helpers;

    public partial class CwfPedidoBien : MaestroDetalleSeguro, IRefrescar
    {
        public CwfPedidoBien()
        {
            InitializeComponent();

            this.dgvDetalle.DataGridView.KeyDown += new KeyEventHandler(DataGridView_KeyDown);
        }

        protected override void LoadPermisos()
        {
            this.TsMenu.Permisos.AddRange(Metodos.GetPermisos(Convert.ToByte(this.Tag)));
        }

        protected override void FocusKeyPress(object sender, KeyPressEventArgs e)
        {
            base.FocusKeyPress(sender, e);
        }

        private void btnBuscar_Click(object sender, EventArgs e)
        {
            try
            {
                this.MaestroBindingSource.DataSource = PedidoManager.Instancia.Buscar(this.dtpDesde.Value, this.dtpHasta.Value, PedidoType.Bien);
                this.dgvMaestro.DataSource = this.MaestroBindingSource;
            }
            catch (Exception ex)
            {
                Mensaje.ShowMessageAlert(this.ParentForm, this.Titulo, ex.Message);
            }
        }

        private void dgvDetalle_EnterKeyPress(object sender, EDOSwit.Controls.EventArgs.EnterKeyPressEventArg e)
        {
            switch (e.ColumnIndex)
            {
                case 1: // Descripcion
                    if (string.IsNullOrEmpty(e.Text))
                    {
                        e.Handle = false;
                    }
                    break;
                case 2: // Cantidad
                    if (string.IsNullOrEmpty(e.Text))
                    {
                        e.Handle = false;
                    }
                    else if (Convert.ToDecimal(e.Text) <= 0)
                    {
                        e.Handle = false;
                    }
                    if (e.Handle)
                    {
                        int count = this.dgvDetalle.DataGridView.Rows.Count;
                        if (this.dgvDetalle.DataGridView.Rows[count - 1].Cells[0].Value != null &&
                            this.dgvDetalle.DataGridView.Rows[count - 1].Cells[1].Value != null)
                        {
                            if (Mensaje.ShowMessageConfirm(this.ParentForm, Constantes.TituloMensaje, "¿Desea agregar un nuevo Detalle?") == DialogResult.Yes)
                            {
                                int index = this.dgvDetalle.DataGridView.Rows.Add();
                                this.dgvDetalle.DataGridView.Rows[index].Cells[0].Value = Convert.ToInt32(this.dgvDetalle.DataGridView.Rows[index - 1].Cells[0].Value) + 1;
                                this.dgvDetalle.DataGridView.Rows[index].Cells[3].Value = AprobacionType.Desaprobado.ToString();
                                this.dgvDetalle.DataGridView.Rows[index].Cells[3].Tag = false;
                            }
                        }
                    }
                    break;
                default:
                    break;
            }
        }

        private void DataGridView_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                if (this.dgvDetalle.DataGridView.CurrentCell != null)
                {
                    if (Mensaje.ShowMessageConfirm(this.ParentForm, this.Titulo, "¿Desea eliminar el Detalle?") == DialogResult.No)
                    {
                        e.Handled = true;
                    }
                    else
                    {
                        this.dgvDetalle.DataGridView.Rows.Remove(this.dgvDetalle.DataGridView.CurrentRow);
                        if (this.dgvDetalle.DataGridView.Rows.Count == 0)
                        {
                            this.dgvDetalle.DataGridView.Rows.Add();
                            this.dgvDetalle.DataGridView.Rows[0].Cells[3].Value = AprobacionType.Desaprobado.ToString();
                            this.dgvDetalle.DataGridView.Rows[0].Cells[3].Tag = false;
                        }
                        foreach (DataGridViewRow row in this.dgvDetalle.DataGridView.Rows)
                        {
                            row.Cells[0].Value = row.Index + 1;
                        }
                    }
                }
            }
        }

        protected override void CellPainting(ref DataGridViewCellPaintingEventArgs e)
        {
            Graphics g = e.Graphics;
            bool selected = ((e.State & DataGridViewElementStates.Selected) == DataGridViewElementStates.Selected);
            Color fcolor = (selected ? e.CellStyle.SelectionForeColor : e.CellStyle.ForeColor);
            Color bcolor = (selected ? e.CellStyle.SelectionBackColor : e.CellStyle.BackColor);
            Font font = e.CellStyle.Font;
            font = new Font("Tahoma", 7);

            Pedido pedido = this.MaestroBindingSource[e.RowIndex] as Pedido;

            if (pedido != null)
            {
                int x = e.CellBounds.Left + e.CellStyle.Padding.Left;
                int y = e.CellBounds.Top + e.CellStyle.Padding.Top;
                int width = e.CellBounds.Width - (e.CellStyle.Padding.Left + e.CellStyle.Padding.Right);
                int height = 13 + (e.CellStyle.Padding.Top + e.CellStyle.Padding.Bottom);

                g.FillRectangle(new SolidBrush(bcolor), e.CellBounds);

                y = y + height - 1;

                if (e.ColumnIndex == 0)
                {
                    font = new Font("Tahoma", 8, FontStyle.Bold);

                    if (selected)
                        TextRenderer.DrawText(e.Graphics, "Nº: " + pedido.IdPedido.ToString().PadLeft(7, '0'), font, new Rectangle(x, y, width, height), fcolor, TextFormatFlags.PreserveGraphicsClipping | TextFormatFlags.EndEllipsis);
                    else
                        TextRenderer.DrawText(e.Graphics, "Nº: " + pedido.IdPedido.ToString().PadLeft(7, '0'), font, new Rectangle(x, y, width, height), System.Drawing.Color.Blue, TextFormatFlags.PreserveGraphicsClipping | TextFormatFlags.EndEllipsis);

                    font = new Font("Tahoma", 8);
                    y = y + height - 1;
                    TextRenderer.DrawText(e.Graphics, pedido.Area != null ? pedido.Area.Nombre : string.Empty, font, new Rectangle(x, y, width, height), fcolor, TextFormatFlags.PreserveGraphicsClipping | TextFormatFlags.EndEllipsis);
                }
                else
                {
                    font = new Font("Tahoma", 9, FontStyle.Bold);
                    if (selected)
                        TextRenderer.DrawText(e.Graphics, pedido.Fecha.ToShortDateString(), font, new Rectangle(x, y, width, height), fcolor, TextFormatFlags.PreserveGraphicsClipping | TextFormatFlags.EndEllipsis);
                    else
                        TextRenderer.DrawText(e.Graphics, pedido.Fecha.ToShortDateString(), font, new Rectangle(x, y, width, height), System.Drawing.Color.Blue, TextFormatFlags.PreserveGraphicsClipping | TextFormatFlags.EndEllipsis);

                    font = new Font("Tahoma", 7);
                    y = y + height - 1;
                    TextRenderer.DrawText(e.Graphics, pedido.Estado ? "Aprobado" : "En Espera", font, new Rectangle(x, y, width, height), fcolor, TextFormatFlags.PreserveGraphicsClipping | TextFormatFlags.EndEllipsis);
                }
            }
        }

        private void ucUbigeo_seleccionarSucursal(object sender, int idSucursal)
        {
            this.cmbArea.Tag = null;
            this.cmbArea.Text = string.Empty;
            Metodos.GetAreas(idSucursal, this.cmbArea.TreeView);
        }

        protected override void InitialLoad()
        {
            try
            {
                this.cmbEstado.DataSource = Enum.GetNames(typeof(AtencionType));

                this.MaestroBindingSource.DataSource = PedidoManager.Instancia.ListarPorTipo(PedidoType.Bien);
                this.dgvMaestro.DataSource = this.MaestroBindingSource;
                OcultarColumnas();
                LoadDataGridView();
            }
            catch (Exception ex)
            {
                Mensaje.ShowMessageAlert(this.ParentForm, this.Titulo, ex.Message);
            }
        }

        private void OcultarColumnas()
        {
            this.dgvMaestro.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            this.dgvMaestro.Columns["Empleados"].Visible = false;
            this.dgvMaestro.Columns["Area"].Visible = false;
            this.dgvMaestro.Columns["Descripcion"].Visible = false;
            this.dgvMaestro.Columns["Estado"].Visible = false;
            this.dgvMaestro.Columns["TipoPedido"].Visible = false;
            this.dgvMaestro.Columns["IdPedido"].HeaderText = "Pedidos";
        }

        private void LoadDataGridView()
        {
            this.dgvDetalle.DataGridView.Rows.Clear();
            this.dgvDetalle.DataGridView.Columns.Clear();
            this.dgvDetalle.Mode = Mode.ReadOnly;

            CustomColumnDataGridView colummn = new CustomColumnDataGridView();
            colummn.Name = "Bien";
            colummn.HeaderText = "Bien";
            colummn.Width = 100;
            colummn.ReadOnly = true;
            colummn.ControlType = CustomControlType.TextBox;
            this.dgvDetalle.CustomColumns.AddColumn(colummn);

            colummn = new CustomColumnDataGridView();
            colummn.Name = "Descripcion";
            colummn.HeaderText = "Descripción";
            colummn.DataType = DataType.Default;
            colummn.ControlType = CustomControlType.TextBox;
            this.dgvDetalle.CustomColumns.AddColumn(colummn);

            colummn = new CustomColumnDataGridView();
            colummn.Name = "Cantidad";
            colummn.HeaderText = "Cantidad";
            colummn.Width = 120;
            colummn.ColumnNext = 2;
            colummn.ControlType = CustomControlType.TextBox;
            colummn.DataType = DataType.Decimales;
            this.dgvDetalle.CustomColumns.AddColumn(colummn);

            colummn = new CustomColumnDataGridView();
            colummn.Name = "Estado";
            colummn.HeaderText = "Estado";
            colummn.Width = 100;
            colummn.ReadOnly = true;
            colummn.ControlType = CustomControlType.TextBox;
            this.dgvDetalle.CustomColumns.AddColumn(colummn);

            this.dgvDetalle.DataGridView.Rows.Add();
            this.dgvDetalle.DataGridView.Rows[0].Cells[0].Value = 1;
            this.dgvDetalle.DataGridView.Rows[0].Cells[3].Value = AprobacionType.Desaprobado.ToString();
            this.dgvDetalle.DataGridView.Rows[0].Cells[3].Tag = false;
            this.dgvDetalle.DataGridView.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
        }

        protected override void EventoNuevo()
        {
            this.cmbEstado.Enabled = false;
            this.cmbEstado.SelectedIndex = (int)AtencionType.EnEspera;
            this.dtpFecha.Enabled = false;
            this.dtpFecha.Value = EmpresaManager.Instancia.Fecha();
            this.dtpFecha.Focus();
        }

        protected override void EventoEditar()
        {
            this.cmbEstado.Enabled = true;
            this.dtpFecha.Enabled = true;
            this.dtpFecha.Focus();
        }

        protected override void EventoGuardar()
        {
            this.dgvDetalle.Mode = Mode.ReadOnly;
        }

        protected override void EventoCancelar()
        {
            this.dgvDetalle.Mode = Mode.ReadOnly;
        }

        protected override void LoadData(object obj)
        {
            Pedido pedido = obj as Pedido;
            if (pedido != null)
            {
                pedido = PedidoManager.Instancia.ObtenerPorID(pedido.IdPedido);

                this.identificador = pedido.IdPedido;
                this.dtpFecha.Value = pedido.Fecha;
                this.cmbArea.SelectedValue = pedido.Area.IdArea;
                this.ucUbigeo.cmbDepartamento.SelectedValue = pedido.Area.Sucursal.Ubigeo.IdDepartamento;
                this.ucUbigeo.cmbProvincia.SelectedValue = pedido.Area.Sucursal.Ubigeo.IdProvincia;
                this.ucUbigeo.cmbDistrito.SelectedValue = pedido.Area.Sucursal.Ubigeo.IdDistrito;
                this.ucUbigeo.cmbSucursal.SelectedValue = pedido.Area.Sucursal.IdSucursal;
                this.cmbArea.SetText(pedido.Area.IdArea.ToString());
                this.txtDescripcion.Text = pedido.Descripcion;

                int index = 0;
                this.dgvDetalle.DataGridView.Rows.Clear();
                foreach (DetallePedido d in pedido.Detalle)
                {
                    index = this.dgvDetalle.DataGridView.Rows.Add(1);
                    this.dgvDetalle.DataGridView.Rows[index].Cells[0].Value = d.IdBien;
                    this.dgvDetalle.DataGridView.Rows[index].Cells[1].Value = d.Descripcion;
                    this.dgvDetalle.DataGridView.Rows[index].Cells[2].Value = Convert.ToInt32(d.Cantidad);
                    this.dgvDetalle.DataGridView.Rows[index].Cells[3].Value = Enum.GetName(typeof(AprobacionType), Convert.ToInt32(d.Estado));
                    this.dgvDetalle.DataGridView.Rows[index].Cells[3].Tag = d.Estado;
                }
                index = this.dgvDetalle.DataGridView.Rows.Add();
                this.dgvDetalle.DataGridView.Rows[index].Cells[0].Value = index + 1;
            }
        }

        protected override bool SaveData()
        {
            bool result = false;
            int posicion = this.MaestroBindingSource.Position;

            try
            {
                switch (this.estadoActual)
                {
                    case EstadoActual.Nuevo:
                        PedidoManager.Instancia.Registrar(GetPedido());
                        break;
                    case EstadoActual.Editar:
                        PedidoManager.Instancia.Modificar(GetPedido());
                        break;
                    case EstadoActual.Eliminar:
                        PedidoManager.Instancia.Eliminar(Convert.ToInt32(this.identificador));
                        this.MaestroBindingSource.RemoveCurrent();
                        posicion -= 1;
                        break;
                }
                result = true;
                InitialLoad();
                this.MaestroBindingSource.Position = posicion;
            }
            catch (Exception ex)
            {
                Mensaje.ShowMessageAlert(this.ParentForm, this.Titulo, ex.Message);
            }
            return result;
        }

        private Pedido GetPedido()
        {
            Pedido pedido = new Pedido
            {
                IdPedido = Convert.ToInt32(this.identificador),
                Fecha = this.dtpFecha.Value,
                TipoPedido = (int)PedidoType.Bien,
                Estado = Convert.ToBoolean(this.cmbEstado.SelectedIndex),
                Descripcion = this.txtDescripcion.Text,
                Area = new Area { IdArea = Convert.ToInt32(this.cmbArea.Tag) },
                Empleados = new Empleados { IdEmpleado = Empresa.Usuario.IdEmpleado }
            };
            foreach (DataGridViewRow row in this.dgvDetalle.DataGridView.Rows)
            {
                if (ValidateData(row.Index))
                {
                    pedido.Detalle.Add(new DetallePedido
                    {
                        IdBien = Convert.ToInt32(row.Cells[0].Value),
                        Descripcion = row.Cells[1].Value.ToString(),
                        Cantidad = Convert.ToDecimal(row.Cells[2].Value),
                        Estado = Convert.ToBoolean(row.Cells[3].Tag)
                    });
                }
            }
            return pedido;
        }

        private bool ValidateData(int rowIndex)
        {
            bool result = true;

            if (this.dgvDetalle.DataGridView.Rows[rowIndex].Cells[0].Value == null)
            {
                result = false;
            }
            if (this.dgvDetalle.DataGridView.Rows[rowIndex].Cells[1].Value == null)
            {
                result = false;
            }
            if (this.dgvDetalle.DataGridView.Rows[rowIndex].Cells[2].Value == null)
            {
                result = false;
            }
            return result;
        }

        protected override bool ValidateData()
        {
            bool result = true;

            if (this.cmbArea.Tag == null)
            {
                this.errValidator.SetError(this.cmbArea, "Seleccionar Area.");
                result = false;
            }
            else
            {
                this.errValidator.SetError(this.cmbArea, string.Empty);
            }
            if (this.cmbEstado.SelectedIndex == -1)
            {
                this.errValidator.SetError(this.cmbEstado, "Seleccionar Estado");
                result = false;
            }
            else
            {
                this.errValidator.SetError(this.cmbEstado, string.Empty);
            }
            int contador1 = 0;
            int contador2 = 0;
            foreach (DataGridViewRow row in dgvDetalle.DataGridView.Rows)
            {
                if (row.Cells[1].Value == null) continue;
                if (ValidateData(row.Index)) contador1++;
                else contador2++;
            }
            if (!(contador1 != 0 && contador2 == 0 && dgvDetalle.DataGridView.Rows.Count > 0))
            {
                Mensaje.ShowMessageAlert(this.ParentForm, Constantes.TituloMensaje, "Debe existir proudctos e ingresados correctamente.");
                result = false;
            }
            return result;
        }

        protected override void ClearControls()
        {
            this.identificador = 0;
            this.cmbArea.TreeView.Nodes.Clear();
            LoadDataGridView();
            base.ClearControls();
        }

        #region Miembros de IRefrescar

        public void Refrescar()
        {
            InitialLoad();
        }

        #endregion
    }
}
